<template>
  <view class="login-page" v-if="level && level == 4 && isShowHome == 0">
    <view class="login-btn">
      <image class="img" src="@/static/login_icon.png"></image>
      <button class="btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"></button>
    </view>
    <!-- <view class="" style="width: 100rpx;height: 100rpx;" @click="handleMessage">
      订阅
    </view> -->
  </view>
	<view class="home" v-else>
		<view class="bg-wrap">
			<u-image width="100%" height="283rpx" src="@/static/image/home/home_bg.png"></u-image>
		</view>
		<view class="" v-if="level && level != 4">
			<!-- 首页轮播图 -->
			<view class="swiper-box">
				<u-swiper height="340" img-mode="widthFix" :list="list" @click="previewImg"></u-swiper>
			</view>
			<!-- 123用户登录显示 -->
			<view v-if="level != 5">
				<!-- 代办事项，公示，统计数据 -->
				<view class="btn-group flex">
					<view class="">
						<image src="https://ydsq.chuangxing.ren/uploads/20240130/c4e55c15336663acd02d9af18a32b890.png" mode="aspectFill" style="width: 400rpx;height: 160rpx;display: block;margin-bottom: 16rpx;" @click="daibsy(1)"></image>
						<image src="https://ydsq.chuangxing.ren/uploads/20240130/ddb3dbd71d298bb0c8c3cfec9aed2aab.png" mode="aspectFill" style="width: 400rpx;height: 160rpx;display: block;" @click="toPublicityPage"></image>
					</view>
					<view class="">
						<image src="https://ydsq.chuangxing.ren/uploads/20240130/3ff7b4eef30dcdfa992fd0e8c255e0b7.png" mode="aspectFill" style="width: 290rpx;height: 336rpx;display: block;" @click="toSspType"></image>
					</view>
					<!-- <view class="left" @click="toBacklogDclare(1)">
						<view class="text">
							<view class="title">
								待办事项
							</view>
							<view class="btn">
								立即处理
							</view>
						</view>
						<view class="img">
							<u-image width="97rpx" height="93rpx" src="@/static/image/home/jihuaxinxi.png"></u-image>
						</view>
					</view>
					<view class="right" @click="toPublicityPage">
						<view class="text">
							<view class="title">
								已办事项
							</view>
							<view class="btn">
								发布公示
							</view>
						</view>
						<view class="img">
							<u-image width="97rpx" height="93rpx" src="@/static/image/home/rizhi.png"></u-image>
						</view>
					</view> -->
				</view>
				<!-- 提示条 -->
				<view class="notice-wrap">
					<u-image width="38rpx" height="38rpx" src="@/static/image/home/tixing.png"></u-image>
					<text>今日新增事件{{newData.day || 0}}条，本周共结办{{newData.week || 0}}条事件！</text>
				</view>
				<!-- 申报进度统计区域 -->
				<view class="declare-count-wrap">
          <view class="item" @click="to(1)" v-if="level == 3">
            <!-- 待办数量 -->
            <view class="num">
              {{countData.daiban || 0}}
            </view>
            <view class="title">
              待办总数
            </view>
            <!-- 待办徽标 -->
            <view class="new">
              {{countData.daiban_red}}
            </view>
          </view>
					<view class="item" @click="toBacklogDclare(1)">
						<!-- 待办数量 -->
						<view class="num" v-if="roleName !== '审核'">
							{{countData.daiban || 0}}
						</view>
						<!-- 待审核数量 -->
						<view class="num" v-if="roleName === '审核'">
							{{countData.daishenhe || 0}}
						</view>
						<view class="title">
							{{roleName === '审核' ? '待审核' : '待办总数'}}
						</view>
						<!-- 待办徽标 -->
						<view class="new" v-if="countData.daiban_red && roleName !== '审核'">
							{{countData.daiban_red}}
						</view>
						<!-- 待审核徽标 -->
						<view class="new" v-if="countData.daiban_red && roleName === '审核' && false">
							{{countData.daiban_red}}
						</view>
					</view>


					<!-- 已经审核 -->
					<view class="item" @click="toBacklogDclare(2)" v-if="roleName === '审核'">
						<view class="num">
							{{countData.tongguo || 0}}
						</view>
						<view class="title">
							已审核
						</view>
						<view class="new" v-if="false">
							{{countData.chulizhong}}
						</view>
					</view>
					<!-- 驳回数 -->
					<view class="item" @click="toBacklogDclare(3)">
						<view class="num">
							{{countData.bohui || 0}}
						</view>
						<view class="title">
							驳回数
						</view>
						<view class="new" v-if="false">
							{{countData.chulizhong}}
						</view>
					</view>

					<!-- 处理中 -->
					<view class="item" @click="toDisposePage">
						<view class="num">
							{{countData.chulizhong || 0}}
						</view>
						<view class="title">
							处理中
						</view>
						<view class="new" v-if="false">
							{{countData.chulizhong}}
						</view>
					</view>

					<view class="item" @click="to(2)">
						<view class="num">
							{{countData.chaoshi || 0}}
						</view>
						<view class="title">
							超时预警
						</view>
						<view class="new" v-if="countData.cuiban_red">
							{{countData.cuiban_red}}
						</view>
					</view>


<!--					<view class="item" @click="toCommentPage">-->
<!--						<view class="num">-->
<!--							{{countData.pinglun || 0}}-->
<!--						</view>-->
<!--						<view class="title">-->
<!--							评论数-->
<!--						</view>-->
<!--						<view class="new" v-if="false">-->
<!--							{{countData.pinglun_red}}-->
<!--						</view>-->
					</view>
				</view>
				<!-- 我的代办区域 -->
				<view class="policy-wrap">
					<view class="title-tools">
						<title-tools title="我的待办" sub-title="更多" :path="path"></title-tools>
					</view>
					<!-- 代办列表 -->
					<view v-if="appealList.length > 0" class="pilicy-list">
						<!-- <pilicy-list v-if="roleName !== '审核'" :list="appealList" :isHome="true" @click="toBacklogDclareDetail"></pilicy-list>
						<list v-else :list="appealList" :isHome="true" @click="toBacklogDclareDetail"></list> -->
						<ssp-item :list="appealList" @click="handleClick" :level='level' @yuying='handelYuyin' @yuyingtime='handleYuyinTim'>
						</ssp-item>
					</view>
					<view v-if="appealList.length == 0" class="no-data">
						<u-empty text="暂无记录" mode="data"></u-empty>
					</view>
				</view>
			</view>
			<!--  -->
			<view v-else>
				<home></home>
			</view>

    <buttom-tip></buttom-tip>
  </view>
</template>

<script>
	import Home from './components/home/Home.vue'
	import PilicyList from '../../components/pilicy-list/PilicyList.vue'
	import TitleTools from '../../components/title-tools/TitleTools.vue'
	import ButtomTip from '@/components/buttom_tip/ButtomTip.vue'
	import List from '@/components/list.vue'
	import SspItem from '@/components/pilicy-list/sspitem.vue'
	import {
		apiGetInformations,
		apiGetNowData,
		apiGetHomeRotation,
		apiGetPhone,
		apiIslogin
	} from '@/api/home/home.js'
	import {
		apiLogin
	} from '@/api/login.js'
	import CONFIG from '@/config/config.js'
	import {
		apiUserAppeal
	} from '@/api/backlog/backlog.js'
	import {
		getAppealByleader
	} from '@/api/audit/audit.js'
	import { dateFormats } from '@/utils/utils.js'
	export default {
		components: {
			TitleTools,
			PilicyList,
			Home,
			ButtomTip,
			List,
			SspItem
		},
		data() {
			return {
				//轮播图数据
				list: [],
				//代办列表
				appealList: [],
				//展示数量数据
				countData: {},
				level: '',
				flag: false,
				watchNum: {
					backlog: 0,
					dispose: 0,
					overtime: 0,
					comment: 0
				},
				newData: {},
				isShowHome: false,
				roleName: '',
				path: 'backlog_declare'
			}
		},
		methods: {
			daibsy(){
				this.$Router.push({
					name: 'backlog_declare',
					params: {
						type: 1
					}
				});
			},
			handleYuyinTim(e){
				console.log('倒计时触发:',e.index)
				if(this.level == 1){
					this.appealList[e.index].flag = false
				}else{
					this.appealList[e.index].appeal.flag = false
				}

			},
			handelYuyin(e){
				console.log(e)
				if(this.level == 1){
					this.appealList[e.index].flag = !e.flag
				}else{
					this.appealList[e.index].appeal.flag = !e.flag
				}
			},
			handleClick(info) {
				console.log(info)
				let id = '';
				if (this.level == 1) {
					id = info.id;
				} else {
					id = info.appeal_id;
				}
				this.$Router.push({
					name: 'backlog_declare_detail',
					params: {
						id
					}
				})
			},
			toSspType(){
				this.$Router.push({
					name: 'ssp_type',
				});
			},
			//跳转待办事项
			toBacklogDclare(type) {
				this.watchNum.backlog = 1;
				if (this.roleName === '审核') {
					this.$Router.push({
						name: 'audit',
						params: {
							type
						}
					});
				} else {
					//  暂时关闭
					// this.$Router.push({
					// 	name: 'backlog_declare',
					// 	params: {
					// 		type
					// 	}
					// });
					this.$Router.push({
						name: 'backlog_declare',
						params: {
							type
						}
					});
				}
			},
      to(type)
      {
        if (type == 1) {
          this.$Router.push({
            name: 'backlog_declare',
            params: {
              type: 1,
            }
          });
        }else{
          this.$Router.push({
            name: 'backlog_declare',
            params: {
              type: 1,
              otime: 1,
            }
          });
        }

      },
			//跳转代办事项详情
			toBacklogDclareDetail(info) {
				let id = '';
				if (info.appeal_id) {
					id = info.appeal_id;
				} else {
					id = info.id
				}
				this.$Router.push({
					name: 'backlog_declare_detail',
					params: {
						id: id
					}
				});
			},
			//跳转公示页面
			toPublicityPage() {
				this.$Router.push({
					name: 'publicity'
				})
			},
			//跳转数据统计页面
			toDataPage() {
				this.$Router.push({
					name: 'data_statistics'
				})
			},
			//跳转处理中页面
			toDisposePage() {
				this.watchNum.dispose = 1;
				this.$Router.push({
					name: 'dispose'
				})
			},
			//跳转超时预警页面
			toOvertimePage(type = 1) {
        if (type == 1) {
          this.watchNum.overtime = 1;
          this.$Router.push({
            name: 'overtime',
            params: {
              type: 'overtime'
            }
          })
        }else{

        }

			},
			//跳转评论页面
			toCommentPage() {
				this.watchNum.comment = 1;
				this.$Router.push({
					name: 'comment'
				})
			},
			//我的待办
			async apiUserAppeal() {
				const res = await apiUserAppeal(1, 10);
				let _data = res.data.list.splice(0, 3)
				let imageRegex = /\.(jpg|jpeg|png|gif)$/i;
				let videoRegex = /(mp4|avi|mov)/i;
				_data.map((v,i)=>{
					let arr = []
					let url = ''
					let type = ''
					if(this.level == 1){
						if(v.material_files.length != 0){
							let zongArr = v.material_files.split(',')
							zongArr.map((vv,ii)=>{
								url = CONFIG.baseUrl +  vv
								if(imageRegex.test(vv)){
									type = 'img'
								}
								if(videoRegex.test(vv)){
									type = 'video'
								}
								arr.push({url,type})
							})
						}
						if(v.voice_file != ''){
							v.voice_file = CONFIG.baseUrl +  v.voice_file
						}
						v.material_files = arr
						v.createtime = dateFormats(v.createtime * 1000,'Y-m-d H:i')
						v.flag = false
					}else{
						if(v.appeal.material_files.length != 0){
							let zongArr = v.appeal.material_files.split(',')
							zongArr.map((vv,ii)=>{
								url = CONFIG.baseUrl +  vv
								if(imageRegex.test(vv)){
									type = 'img'
								}
								if(videoRegex.test(vv)){
									type = 'video'
								}
								arr.push({url,type})
							})
						}
						if(v.appeal.voice_file != ''){
							v.appeal.voice_file = CONFIG.baseUrl +  v.appeal.voice_file
						}

						v.appeal.material_files = arr
						v.appeal.createtime = dateFormats(v.createtime * 1000,'Y-m-d H:i')
						v.appeal.flag = false
					}
				})
				this.appealList = _data;
				console.log("(this.appealList", this.appealList)
			},
			//获取部门领导待审核列表
			async getAppealByleader () {
				const res = await getAppealByleader(1, 1, 10);
				this.appealList = res.data.list.splice(0, 3);
			},
			//获取代办 - 处理中 数量
			async apiGetInformations() {
				const res = await apiGetInformations();
				this.countData = res.data;
				console.log(res)
			},
			//使用code换取openid和session_key
			async apiLogin(code) {
				const res = await apiLogin(code);
				await this.apiIslogin();
				let level = '';
				if (this.isShowHome == 1) {
					level = 1;
				} else {
					level = res.data.userinfo.level || res.data.userinfo;
				}
				let levelName = ''

				switch (level) {
					case '1':
						levelName = '超级管理员'
						break;
					case '2':
						levelName = '部门干事'
						break;
					case '3':
						levelName = '部门领导'
						break;
					case '4':
						levelName = '暂无'
						break;
					case '5':
						levelName = '园区领导'
						break;
					default:
						break;
				}
				if (level != 4) {
					getApp().globalData.username = res.data.userinfo.name;
					getApp().globalData.avatar = res.data.userinfo.avatar;
					getApp().globalData.organization_classify_id = res.data.userinfo.organization_classify_id;
				}
				//存储token
				uni.setStorageSync('token', res.data.token);
				// //保存认证状态
				// getApp().globalData.status = res.data.status;
				getApp().globalData.levelName = levelName;
				if (level == 3) {
					getApp().globalData.roleName = '审核';
					this.roleName = '审核';
					// this.path = 'audit';
					// getApp().globalData.level = 2;
				} else {
					//用户级别
					getApp().globalData.level = level;
				}
        getApp().globalData.level = level;
        this.level = getApp().globalData.level;
				getApp().globalData.baseUrl = CONFIG.baseUrl;
			},
			//获取新增数据
			async apiGetNowData() {
				const res = await apiGetNowData();
				this.newData = res.data;
			},
			async apiGetHomeRotation() {
				const res = await apiGetHomeRotation();
				res.data.forEach(item => {
					item.image = CONFIG.baseUrl + item.image
					this.list.push(item.image);
				})
				// this.list = res.data;
				console.log('res:',res);
			},
			async apiGetPhone(iv, encryptedData) {
				const res = await apiGetPhone({
					iv,
					encryptedData
				});
				if (!res.data) {
					wx.showModal({
						title: '提示',
						showCancel: false,
						content: res.msg,
					})
				}
			},
			//订阅消息
			handleMessage () {
				wx.getSetting({
					withSubscriptions: true, //是否同时获取用户订阅消息的订阅状态，默认不获取
					success: (res) => {
						console.log(res)
						if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
							res.subscriptionsSetting.itemSettings[message] == "reject") {
							//打开设置去设置
							this.openConfirm('检测到您没打开推送权限，是否去设置打开？')
						} else {
							wx.requestSubscribeMessage({
								tmplIds: ['3u7gV3ggWcQsP0b3BcwZzfGS8uEtVMv25m-VK5mwQFo'],
								success: (res) => {
									console.log(res)
									// if (res[message] == 'accept') {
									// 	//用户允许
									// }
								},
								fail: (res) => {
									console.info(res)
								},
							})
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			//获取手机号
			async onGetPhoneNumber(e) {

				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
					wx.showModal({
						title: '提示',
						showCancel: false,
						content: '未授权',
					})
				} else {
					await this.apiGetPhone(e.detail.iv, e.detail.encryptedData);
					this.login();
					// wx.showModal({
					// 	title: '提示',
					// 	showCancel: false,
					// 	content: '同意授权',
					// 	success: function(res) {}
					// })

				}
			},
			//打开设置
			openConfirm(message) {
				wx.showModal({
					content: message,
					confirmText: "确认",
					cancelText: "取消",
					success: (res) => {
						//点击“确认”时打开设置页面
						if (res.confirm) {
							wx.openSetting({
								success: (res) => {
									console.log(res.authSetting)
								},
								fail: (error) => {
									console.log(error)
								}
							})
						} else {
							console.log('用户点击取消')
						}
					}
				});
			},
			login() {
				const that = this;
				uni.login({
					async success(res) {
						console.log(res.code)
						await that.apiLogin(res.code);
						uni.hideLoading();
						that.apiGetHomeRotation();
						if (that.level != 5) {
							that.flag = true;
							if (that.roleName == '审核') {
								// that.getAppealByleader();
								that.apiUserAppeal();
							} else {
								//获取待办
								that.apiUserAppeal();
							}

							//获取代办 - 处理中 数量
							that.apiGetInformations();
							//获取新增数据
							that.apiGetNowData();
						}
					}
				})
			},
			async apiIslogin () {
				const res = await apiIslogin();
				this.isShowHome = res.data;
				console.log(res)
			},
			//预览图片
			previewImg (index) {
				uni.previewImage({
					current: this.list[index],
					urls:	this.list
				})
			}
		},
		onShow() {
			if (this.flag) {
				if (this.roleName === '审核') {
					//获取审核列表
					// this.getAppealByleader();
					this.apiUserAppeal();
				} else {
					//获取待办
					this.apiUserAppeal();
				}

				//获取代办 - 处理中 数量
				this.apiGetInformations();
				//获取新增数据
				this.apiGetNowData();
			}

		},
		async onLoad() {
			//登录
			uni.showLoading({
				title: '加载中'
			})
			this.login()

		},
		onTabItemTap: function(item) {
			uni.$emit('updateData')
		},
		watch: {
			watchNum: {
				handler(newValue) {
					console.log(newValue)
					if (newValue.backlog) {
						this.countData.daiban_red = 0;
					}
					if (newValue.dispose) {

					}
					if (newValue.overtime) {
						this.countData.cuiban_red = 0;
					}
					if (newValue.comment) {
						this.countData.pinglun_red = 0;
					}
				},
				deep: true
			}
		}

	}
</script>

<style lang="scss" scoped>
	.home {
		padding: 0 20rpx;
	}

	.bg-wrap {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		z-index: -99;
	}

	// 代办事项，公示，统计数据按钮样式
	.btn-group {
		display: flex;
		justify-content: space-between;
		margin-top: 35rpx;

		.left {
			position: relative;
			display: flex;
			width: 350rpx;
			height: 180rpx;
			background: linear-gradient(180deg, #72AEFF 0%, #377CFF 100%);
			border-radius: 20rpx;

			.text {
				flex: 1;
				padding: 42rpx 0 0 36rpx;

				.title {
					font-size: 34rpx;
					font-weight: 500;
					color: #FFFFFF;
				}

				.btn {
					margin-top: 20rpx;
					font-size: 26rpx;
					font-weight: 500;
					color: #196EFF;
					line-height: 40rpx;
					width: 140rpx;
					height: 40rpx;
					text-align: center;
					background: #FFFFFF;
					border-radius: 20rpx;
				}
			}

			.img {
				flex: 1;
				position: absolute;
				right: 13rpx;
				bottom: 0;
			}
		}

		.right {
			position: relative;
			display: flex;
			width: 350rpx;
			height: 180rpx;
			background: linear-gradient(0deg, #17BE91 0%, #52DEC8 100%);
			border-radius: 20rpx;

			.text {
				flex: 1;
				padding: 42rpx 0 0 36rpx;

				.title {
					font-size: 34rpx;
					font-weight: 500;
					color: #FFFFFF;
				}

				.btn {
					margin-top: 20rpx;
					font-size: 26rpx;
					font-weight: 500;
					color: #18BE91;
					line-height: 40rpx;
					width: 140rpx;
					height: 40rpx;
					text-align: center;
					background: #FFFFFF;
					border-radius: 20rpx;
				}
			}

			.img {
				flex: 1;
				position: absolute;
				right: 13rpx;
				bottom: 0;
			}
		}
	}

	// 提示条样式
	.notice-wrap {
		display: flex;
		align-items: center;
		padding: 0 24rpx;
		margin-top: 30rpx;
		width: 710rpx;
		height: 60rpx;
		background: #FFFFFF;
		border-radius: 30rpx;

		text {
			margin-left: 18rpx;
		}
	}

	//申报进度统计区域样式
	.declare-count-wrap {
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		width: 710rpx;
		height: 200rpx;
		background: #FFFFFF;
		border-radius: 20rpx;

		.item {
			position: relative;
			display: flex;
			flex-direction: column;
			justify-content: center;
			flex: 1;
			text-align: center;
			height: 100%;

			.num {
				font-size: 60rpx;
				font-family: D-DIN;
				font-weight: bold;
				color: #000000;
			}

			.title {
				margin-top: 10rpx;
				font-size: 26rpx;
				color: #000000;
			}

			.new {
				position: absolute;
				right: 10rpx;
				top: 20rpx;
				padding: 0 5rpx;
				font-size: 24rpx;
				font-family: D-DIN;
				font-weight: bold;
				color: #FFFFFF;
				// width: 30rpx;
				height: 30rpx;
				background: #FF0000;
				border-radius: 15rpx 15rpx 15rpx 6rpx;
			}
		}
	}

	//最新政策区域
	.policy-wrap {
		margin-top: 51rpx;

		.title-tools {}

		.pilicy-list {
			margin-top: 30rpx;
		}
	}

	.no-data {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 51rpx;
		padding: 30rpx;
		width: 710rpx;
		// height: calc(100vh - 106rpx);
		// overflow-y: auto;
		min-height: 686rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
	}

	.login-page {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		margin-top: 20rpx;
		width: 710rpx;
		height: calc(100vh - 40rpx);
		background-color: #fff;
		border-radius: 20rpx;

		.login-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			width: 170rpx;
			height: 170rpx;
			opacity: 1;
			border: 4rpx solid #EAF1F9;
			border-radius: 50%;

			.img {
				width: 60%;
				height: 60%;
			}

			.btn {
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;
				background-color: transparent;
				border: none;
				outline: none;

				&::after {
					border: none;
				}
			}
		}
	}
</style>
